package com.sctu.http;

import android.os.Handler;
import android.os.Message;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhu on 2015/11/7.
 */
public class HttpUtil {
    public HttpUtil() {}
    private static  HttpUtil single;
    //静态工厂方法
    public static HttpUtil getInstance() {
        if (single == null){
            single = new HttpUtil();
        }
        return single;
    }
    private ExecutorService e = new ThreadPoolExecutor(3, 5, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100000),

            new ThreadPoolExecutor.CallerRunsPolicy());

    public void getRequest(final String path,final Handler handler){

        e.execute(new Runnable() {
            @Override
            public void run() {

                HttpClient httpClient = new DefaultHttpClient();
                Message message = new Message();
                HttpGet httpGet = new HttpGet(path);

                try {
                    ConnManagerParams.setTimeout(httpClient.getParams(), 20 * 1000);
                    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10 * 1000);
                    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 10 * 1000);

                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    String strResult = EntityUtils.toString(httpResponse.getEntity());



                    message.obj = strResult;
                    message.arg1 = 0;

                } catch (IOException e) {
                    message.arg1 = 1;

                }
                handler.sendMessage(message);

            }
        });
    }

    public void postRequest(final String path,final Handler handler,final HashMap<String,String> postMap){
        e.execute(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(path);

                List<BasicNameValuePair> postMsg = getPostParams(postMap);

                try {
                    ConnManagerParams.setTimeout(httpClient.getParams(), 20 * 1000);
                    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10 * 1000);
                    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 10 * 1000);

                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postMsg,"utf-8");
                    httpPost.setEntity(entity);
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    String strResult = EntityUtils.toString(httpResponse.getEntity());

                    message.obj = strResult;
                    message.arg1 = 0;


                } catch (UnsupportedEncodingException e) {
                    message.arg1 = 1;

                }
                catch (IOException e) {
                    message.arg1 = 1;

                }
                handler.sendMessage(message);
            }
        });
    }

    private List<BasicNameValuePair> getPostParams(HashMap<String,String> postMap){
        List<BasicNameValuePair> postMsg = new ArrayList<BasicNameValuePair>();
        Iterator iterator = postMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String,String> entry = (Map.Entry<String, String>) iterator.next();
            postMsg.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        return postMsg;
    }

}
